<template>
    <GhNavBar title="编辑个人信息" rightText="保存" @click-right="clickRight" />
    <div class="editUserInfo">
        <!-- <h1>编辑个人信息</h1> -->
        <div class="editForm">
        <van-form ref="form" >
          <van-field v-model="userInfoData.username" readonly clickable input-align="right"  label="用户名" required label-width="100px" autocomplete="off"  @click="showUsername = true" is-link></van-field>
          <van-popup v-model:show="showUsername" @click-close-icon="true" closeable  round position="bottom">
            <h1>修改昵称</h1>
            <van-field v-model="currentUsername"  label="用户名" label-width="60px" maxlength="25" autocomplete="off"  ></van-field>
            <van-button native-type="submit" @click="saveUsername" block round type="primary">
                确定
              </van-button>
        </van-popup>
          <van-field v-model="userInfoData.reduce" readonly clickable  input-align="right" type="text" label="*个人简介" @click="showReduce = true" placeholder="一句话介绍我自己" is-link  autocomplete="off"></van-field>
          <!-- 个人简介编辑器 -->
          <van-popup v-model:show="showReduce" @click-close-icon="closeReduce=true" closeable  round position="bottom">
          <h1>编辑个人简介</h1>
          <van-field
             v-model="currentReduce"
             rows="4"
             class="custom-field"
             autosize
             maxlength="70"
             type="textarea"
             show-word-limit
             placeholder="一句话介绍我自己"
         />
         <van-button native-type="submit" @click="saveReduce" block round type="primary">
            保 存
          </van-button>
        </van-popup> 
          <van-field  is-link readonly v-model="userInfoData.birthday"  label="*生日" input-align="right"  placeholder="待完善" @click="showPicker = true">  
          </van-field>
          <!-- 展示生日日期选择器   -->
            <van-popup v-model:show="showPicker" round position="bottom">
                <van-datetime-picker
                v-model="currentDate"
                type="date"
                title="请选择您的生日"
                :min-date="minDate"
                :max-date="maxDate"
                @cancel="showPicker=false"
                @confirm="onConfirm"
                :formatter="formatter"
              />
            </van-popup> 
        
          <van-field v-model="userInfoData.email" input-align="right" :rules="emailRule.value"   label="邮箱"  type="email" required label-width="20px" is-link></van-field>
          <van-field v-model="userInfoData.gender"   name="radio" label="性别" input-align="right" required  is-link>
                <template #input>
                  <van-radio-group v-model="userInfoData.gender" direction="horizontal" >
                    <van-radio name="男">男</van-radio>
                    <van-radio name="女">女</van-radio>
                  </van-radio-group>
                </template>
           </van-field> 
           
        </van-form>
         </div>
        </div>
</template>

<script setup>

import GhNavBar from '@/components/gh-nav-bar.vue'
import {ref,computed,onMounted,onUnmounted} from 'vue'
import { Toast, Dialog } from 'vant';
import { editUserInfo } from '@/services/user'
import {useRouter,useRoute} from 'vue-router'
//跳转路由使用
const router=useRouter();
// 获取路由参数
const route = useRoute()
// import "@vant/touch-emulator";
const userInfo=JSON.parse(localStorage.getItem('gh-user')).user.userData

const user=ref()
user.value=userInfo
// console.log(user.value)
//定义编辑用户的信息
const userInfoData=ref({
    username:user.value.username,
    account:user.value.account,
    reduce:user.value.reduce,
    birthday:user.value.birthday,
    email:user.value.email,
    gender:user.value.gender
})
const currentReduce=ref('')
const saveReduce=async()=>{
 userInfoData.value.reduce=currentReduce.value
 Toast('个人简介设置成功')
 showReduce.value=false
}
const currentUsername=ref('')
//保存用户名
const saveUsername=async()=>{
    console.log(currentUsername.value)
 userInfoData.value.username=currentUsername.value
 Toast('昵称已设置')
 showUsername.value=false
}
//定义用户名修改编辑器
const showUsername=ref(false)
//定义个人简介编辑器
const showReduce=ref(false)
//定义展示生日选择器
const showPicker=ref(false)
//定义生日时间
// const birthday=ref()
const currentDate=ref(new Date(2024,0,5))
const minDate = new Date(1949, 10, 1)
const maxDate = new Date()
const formatter = (type, val) => {
      if (type === 'year') {
        return `${val}年`;
      }
      if (type === 'month') {
        return `${val}月`;
      }
      if (type === 'day') {
        return `${val}日`;
      }
      return val;
    };
// 将 Date 对象转换为指定格式的字符串
const formattedDate = computed(() => {
      const year = currentDate.value.getFullYear();
      const month = String(currentDate.value.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.value.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    });


    // 处理选择生日后的逻辑
const onConfirm = (value) => {
    // console.log(value)
    const date = new Date(value);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');  
    const formattedDate = `${year}-${month}-${day}`;

  userInfoData.value.birthday=formattedDate
  showPicker.value=false
};

//邮箱验证规则
const emailRule=ref([{
    required:true,
    message:'邮箱不能为空'
},{
    pattern:/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/,
    message:'邮箱格式错误'
}])

computed(()=>{
    return emailRule.value
})


//点击右上角保存修改个人信息
const clickRight=async()=>{
  //  console.log(userInfoData.value)
   const formData=new FormData();
   formData.append('username',userInfoData.value.username)
   formData.append('account',userInfoData.value.account)
   formData.append('reduce',userInfoData.value.reduce)
   formData.append('birthday',userInfoData.value.birthday)
   formData.append('email',userInfoData.value.email)
   formData.append('gender',userInfoData.value.gender)
//    for (const pair of formData.entries()) {
//           console.log('注册前的表单数据：',pair[0], pair[1]);}
//    console.log(formData)
   const res=await editUserInfo(formData).then((response)=>{
      return response
    }).catch((error)=>{
     return error
    })
   console.log(res)
   if(res.status!==201){
   if(res.response.status==402){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
    }
}
    Toast.success('个人信息修改成功')
    router.push('/user')
}

</script>

<style lang="scss" scoped>
/* @import "~vant/lib/datetime-picker/index.css"; */
 .editUserInfo{
        padding-top:48px;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        .editForm{
           /* width: 90%; */
           text-align: center;
         h1{
         margin-top: 20px;
         margin-bottom: 10px;
         font-size: 17px;
         font-weight: 600;
         font-family: 宋体;
         
         }
         .van-button{
           left: 50%;
           transform: translate(-50%);
           width: 90%;
           height: 36px;
           margin-bottom: 10px;
           font-size: 16px;
         }
     }

}
      
        


</style>
